package com.app.system.utils.mysql;

import com.app.system.config.properties.SystemParamProperties;
import com.app.system.log4j2.LogUtils;
import com.app.system.permission.model.DataBase;
import com.app.system.permission.service.DataBaseService;
import com.app.system.utils.dataType.DateUtils;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.Map;

/**
 * 数据库备份基本参数
 * Created by wcf-pc on 2019/1/27.
 */
@Component
@SuppressWarnings("all")
@PropertySource(value = {"classpath:application-prod.yml"}, ignoreResourceNotFound = true, encoding = "utf-8")
public class MySqlProperty {

    private Logger logger = LogUtils.getDBLogger();

    @Resource
    DataBaseService dataBaseService;

    @Resource
    SystemParamProperties systemParamProperties;

    @Value("${spring.datasource.url}")
    private String url;//数据库访问地址，需要提取出ip、port、数据库名称
    @Value("${spring.datasource.username}")
    private String username;//数据库用户名
    @Value("${spring.datasource.password}")
    private String password;//数据库密码

    /**
     * 对url进行解析：ip、port、dataBaseName
     *
     * @return
     */
    public Map<String, String> analyticUrl() {
        Map<String, String> result = Maps.newHashMap();
        if (url != null && !url.isEmpty()) {
            String u = url.trim();//去掉两边空格
            String a = u.substring(13, u.indexOf("?"));
            String ip = a.substring(0, a.indexOf(":"));
            String port = a.substring(a.indexOf(":") + 1, a.indexOf("/"));
            String dataBaseName = a.substring(a.indexOf("/") + 1);
            result.put("ip", ip);
            result.put("port", port);
            result.put("dataBaseName", dataBaseName);
        }
        return result;
    }

    public boolean back() {
        Date date = new Date();
        String formaterDate = DateUtils.dateToStringFormat(date, "yyyy_MM_dd_HH_mm_ss_SSS");
//        String user = SecurityUtils.getSubject().getPrincipal().toString();//操作用户
        logger.info("**************备份开始！**************" + formaterDate);
        try {
            Map<String, String> analyticUrl = analyticUrl();
            String dataBaseName = analyticUrl.get("dataBaseName");
            String year = DateUtils.dateToStringFormat(date, "yyyy");
            String month = DateUtils.dateToStringFormat(date, "MM");
            String day = DateUtils.dateToStringFormat(date, "dd");
            String path = systemParamProperties.getMysqlBackDataPath() + "/" + year + "/" + month + "/" + day + "/";//以数据库名称为目录名
            String fileName = dataBaseName + "_backup_" + formaterDate + ".sql";
            boolean result = MySqlBackUtils.dbBackup(
                    analyticUrl.get("ip"),
                    Integer.valueOf(analyticUrl.get("port")),
                    getUsername(),
                    getPassword(),
                    path,
                    fileName, dataBaseName);
            if (result) {
                File file = new File(path + fileName);
                DataBase dataBase = new DataBase();
                dataBase.setFileDate(date);
                dataBase.setFileDateLong(date.getTime());
                dataBase.setFileSize(file.length());
                dataBase.setFileName(fileName);
                dataBase.setFilePath(file.getAbsolutePath());
                this.dataBaseService.save(dataBase);
                logger.info("数据库成功备份！！！");
            } else {
                logger.info("数据库备份失败！！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("**************备份结束！**************" + DateUtils.dateToStringFormat(date, "yyyy_MM_dd_HH_mm_ss_SSS"));
        return true;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
